#!/bin/sh

USER='emby'
GROUP='emby'

usage() {
  echo 'Usage: emby-migrate-database {-u user} {-g group} old_path_full new_path_full'
  echo 'Default user: emby'
  echo 'Default group: emby'
}

migrate() {
  if [[ $1 && $2 ]]; then
    if [[ -f $1/data/library.db ]]; then
      if [[ ! -e $2 ]]; then
        mkdir -p $2
      fi
      if [[ -d $2 ]]; then
        if [[ -z $(ls $2) ]]; then
          cp -r $1/* $2/
          sqlite3 $2/data/library.db "UPDATE TypedBaseItems SET data = CAST(REPLACE(CAST(data AS TEXT), '$1', '$2') AS BLOB);"
          chown $USER:$GROUP -R $2
          echo "Migration complete. You can now delete $1."
        else
          echo "$2 is not empty. Aborting."
        fi
      else
        echo "$2 is not a directory. Aborting."
      fi
    else
      echo "$1 does not contain an emby database. Aborting."
    fi
  else
    usage
  fi
}

if [[ $1 == '--help' ]]; then
  usage
else
  while getopts 'u:g:' opt; do
    case $opt in
      u)
        USER=$OPTARG
        ;;
      g)
        GROUP=$OPTARG
        ;;
      \?)
        usage
        ;;
    esac
  done
  shift $((OPTIND-1))
  migrate
fi
